home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_04 / saks / z2.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-02  |  1.8 KB  |  100 lines

  1. Listing 4 -  A rudimentary class for complex numbers using
  2. "lazy" evaluation and caching for polar form
  3.  
  4. // z2.cpp
  5.  
  6. #include <iostream.h>
  7. #include <iomanip.h>
  8. #include <math.h>
  9.  
  10. class complex
  11.     {
  12. public:
  13.     complex(double r, double i);
  14.     complex(const complex &z);
  15.     complex &operator=(const complex &z);
  16.     ~complex();
  17.     double real() const;
  18.     double imag() const;
  19.     double rho() const;
  20.     double theta() const;
  21. private:
  22.     double re, im;
  23.     struct polar;
  24.     polar *p;
  25.     };
  26.  
  27. struct complex::polar
  28.     {
  29.     polar(double r, double t);
  30.     double rho, theta;
  31.     };
  32.  
  33. inline complex::polar::polar(double r, double t)
  34.     : rho(r), theta(t)
  35.     {
  36.     }
  37.  
  38. inline complex::complex(double r, double i)
  39.     : re(r), im(i), p(0)
  40.     {
  41.     }
  42.  
  43. inline complex::complex(const complex &z)
  44.     : re(z.re), im(z.im), p(0)
  45.     {
  46.     }
  47.  
  48. inline complex &complex::operator=(const complex &z)
  49.     {
  50.     re = z.re;
  51.     im = z.im;
  52.     p = 0;
  53.     return *this;
  54.     }
  55.  
  56. inline complex::~complex()
  57.     {
  58.     delete p;
  59.     }
  60.  
  61. inline double complex::real() const
  62.     {
  63.     return re;
  64.     }
  65.  
  66. inline double complex::imag() const
  67.     {
  68.     return im;
  69.     }
  70.  
  71. double complex::rho() const
  72.     {
  73.     if (p == 0)
  74.         {
  75.         complex *This = const_cast<complex *>(this);
  76.         This->p =
  77.             new polar(sqrt(re*re + im*im), atan2(im, re));
  78.         }
  79.     return p->rho;
  80.     }
  81.  
  82. double complex::theta() const
  83.     {
  84.     if (p == 0)
  85.         (polar *&)p =
  86.              new polar(sqrt(re*re + im*im), atan2(im, re));
  87.     return p->theta;
  88.     }
  89.  
  90. complex operator+(const complex &z1, const complex &z2)
  91.     {
  92.     return complex
  93.         (z1.real() + z2.real(), z1.imag() + z2.imag());
  94.     }
  95.  
  96. int main()
  97.     {
  98.     // same as Listing 3
  99.     }
  100.